var UserManager = function() {
	this.table;
	this.form;
	this.laytpl;
	this.formSelects;
	this.element;
	this.layer;
	this.userTable;
};
UserManager.prototype = {
	init : function(element, table, form, laytpl, formSelects, layer) {
		this.table = table;
		this.form = form;
		this.laytpl = laytpl;
		this.formSelects = formSelects;
		this.layer = layer;
		this.element = element;

		this.initRender();
		this.initEvent();
	},
	initRender : function() {
		this.userTable = this.table.render({
			id : "usertable",
			elem : '#allUser',
			height : 'full-215',
			url : '/users/queryAll', // 数据接口
			page : true, // 开启分页
			limit : 10,
			cellMinWidth : 80,
			even : true,
			toolbar: '#userTopTool',
			cols : [ [ // 表头
			{
				type : 'checkbox',
				fixed : 'left',
			}, {
				field : 'username',
				title : '用户名',
				sort : true
			}, {
				field : 'statsu_desc',
				title : '状态',
				sort : true
			}, {
				field : 'role',
				title : '角色',
				sort : true
			}, {
				field : 'create_time',
				title : '创建时间',
				sort : true
			}, {
				field : 'last_time',
				title : '最后登录时间',
				sort : true
			}, {
				field : 'login_count',
				title : '登录次数',
				sort : true
			}, {
				field : 'login_ip',
				title : '最后登录IP',
				sort : true
			}, {
				field : 'lock',
				title : '是否冻结',
				templet : '#checkboxTpl'
			}, {
				title : '操作',
				toolbar : '#userToolbar'
			} ] ],
			response : {
				statusName : 'status', // 数据状态的字段名称，默认：code
				statusCode : 200, // 成功的状态码，默认：0
				msgName : 'message', // 状态信息的字段名称，默认：msg
				countName : 'total', // 数据总数的字段名称，默认：count
				dataName : 'data', // 数据列表的字段名称，默认：data
			},
			loading : true
		});
	},
	initEvent : function() {
		var that = this;
		// 监听表格复选框选择
		that.table.on('checkbox(allUser)', function(obj) {
			console.log(obj)
		});
		// 监听工具条
		that.eventTool();

		var $ = layui.$, active = {
			addUser : function() {
				that.addUser();
			},
			deleteUser : function() {
				var checkStatus = that.table.checkStatus('usertable');
				var data = checkStatus.data;

				if (data.length > 0) {
					var ids = [];
					$.each(data, function(i, item) {
						ids.push(item.id);
					});
					that.layer.confirm("确定删除选中的用户？", function(index) {
						that.deleteSeletedUser(ids, data);
						that.layer.close(index);
					});
				} else {
					that.layer.alert("没有选择要删除的用户");
				}
			},
			flushUser : function() {
				that.userTable.reload({
					loading : true
				});
			},
			exportUser:function(){
				var headersName = ['ID','用户名','状态','角色','创建时间','最后登录时间','登录次数','最后登录IP','是否冻结'];
				var headersId = ['id','username','statsu_desc','role','create_time','last_time','login_count','login_ip','lock'];
				var data = {
						headersName:headersName,
						headersId:headersId
				}
				$.ajax({
					url : '/users/export',
					type:"post",
					data:{
						headersName:JSON.stringify(['ID','用户名','状态','角色','创建时间','最后登录时间','登录次数','最后登录IP','是否冻结']),
						headersId:JSON.stringify(['id','username','statsu_desc','role','create_time','last_time','login_count','login_ip','lock'])
					},
					dataType:"json",
					success:function(){
						
					}
				});
			}
		};
		that.table.on('toolbar(allUser)', function(obj){
			var type = obj.event;
			active[type] ? active[type].call(this) : '';
		});
		that.eventLock();
	},
	eventTool : function() {
		var that = this;
		this.table.on('tool(allUser)', function(obj) {
			var data = obj.data;
			if (obj.event === 'del') {
				layer.confirm('确定删除用户"' + data.username + '"？',
						function(index) {
							that.deleteUser(obj);
							that.layer.close(index);
						});
			} else if (obj.event === 'edit') {
				that.editUser(obj);
			}
		});
	},
	eventLock : function() {
		// 监听锁定操作
		this.form.on('checkbox(lockUser)', function(obj) {
			layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked,
					obj.othis);
		});
	},
	editUser : function(obj) {
		var that = this;
		var data = obj.data;
		var html = getHtml("/system/editUser.html");
		var index = layer.open({
			id : "editUser",
			title : "修改" + data.username,
			type : 1,
			content : html,
			area : [ '450px', '300px' ]
		});
		that.initSelect(data);

		$("#editUser input[name='username']").val(data.username);
		$("#editUser input[name='password']").val(data.password);
		if(data.id == 1){
			$("#editUser input[name='username']").addClass("layui-disabled");
			this.formSelects.disabled('roleid');
		}
		that.form.render();
		that.eventEditUser(obj, index);

		$("#edit_cancel").click(function() {
			that.layer.close(index);
			return false;
		});
	},
	addUser : function() {
		var that = this;
		var html = getHtml("/system/addUser.html");
		var index = layer.open({
			id : "addUser",
			title : "新增用户",
			type : 1,
			content : html,
			area : [ '450px', '300px' ]
		});
		that.initSelect();

		that.form.render();

		that.eventAddUser(index);

		$("#add_cancel").click(function() {
			that.layer.close(index);
			return false;
		});
	},
	initSelect:function(data){
		var that = this;
		var defval = [];
		if(data){
			defval.push(data.roleid);
		}
		this.formSelects.config('roleid', {
            beforeSuccess: function(id, url, searchVal, result){
                return result.data; 
            },
            success:function(id, url, val, result){
            	that.formSelects.value('roleid', defval);
            },
        }).data('roleid', 'server', {
            url: '/roles/queryAllRole'
        });
	},
	/*
	 * 监听提交新增用户
	 */
	eventAddUser : function(index) {
		var that = this;
		that.form.on('submit(add_ok)', function(data) {
			data.field.status = 0;
			that.layer.close(index);
			var loadindex = that.layer.load(0);
			$.ajax({
				url : '/users/add',
				type : "post",
				dataType : "json",
				data : data.field,
				success : function(response) {
					that.layer.close(loadindex);
					var status = response.status;
					if (status == 200) {
						that.userTable.reload({
							loading : true
						});
					} else {
						that.layer.alert(response.message);
					}
				},
				error : function(xhr, textStatus) {
					that.layer.close(loadindex);
					that.layer.alert(textStatus);
				}
			});
			return false;
		});
	},
	eventEditUser : function(obj, index) {
		var that = this;
		var id = obj.data.id;
		that.form.on('submit(edit_ok)', function(data) {
			data.field.id = id;
			that.layer.close(index);
			var loadindex = that.layer.load(0);
			$.ajax({
				url : '/users/update',
				type : "post",
				dataType : "json",
				data : data.field,
				success : function(response) {
					that.layer.close(loadindex);
					var status = response.status;
					if (status == 200) {
						that.userTable.reload({
							loading : true
						});
					} else {
						that.layer.alert(response.message);
					}
				},
				error : function(xhr, textStatus) {
					that.layer.close(loadindex);
					that.layer.alert(textStatus);
				}
			});
			return false;
		});
	},
	deleteUser : function(obj) {
		var that = this;
		var loadindex = that.layer.load(0);
		$.ajax({
			url : "/users/delete?id=" + obj.data.id,
			type : "get",
			dataType : "json",
			success : function(response) {
				that.layer.close(loadindex);
				var status = response.status;
				if (status == 200) {
					obj.del();
				} else {
					that.layer.alert(response.message);
				}
			},
			error : function(xhr, textStatus) {
				that.layer.close(loadindex);
				that.layer.alert(textStatus);
			}
		});
	},
	deleteSeletedUser : function(ids, data) {
		var that = this;
		var loadindex = that.layer.load(0);
		$.ajax({
			url : "/users/deleteUser",
			type : "post",
			dataType : "json",
			contentType: "application/json;charset=UTF-8",
			data :JSON.stringify(ids),
			success : function(response) {
				that.layer.close(loadindex);
				var status = response.status;
				if (status == 200) {
					that.userTable.reload({
						loading : true
					})
				} else {
					that.layer.alert(response.message);
				}
			},
			error : function(xhr, textStatus) {
				that.layer.close(loadindex);
				that.layer.alert(textStatus);
			}
		});
	}
}